layui.use(['element', 'table', 'layer', 'form', 'zltreemenu','upload', 'zlPinYin', 'zlConfig', 'zlContext', 'treeGrid'], function (exports) {
    var $ = layui.$,
        zlContext = layui.zlContext,
        zltreemenu = layui.zltreemenu,
        layer = layui.layer,
        form = layui.form,
        zlPinYin = layui.zlPinYin,
        zlConfig = layui.zlConfig,
        treeGrid = layui.treeGrid,
        statusName = zlConfig.global.result.statusName,
        msgName = zlConfig.global.result.msgName,
        dataName = zlConfig.global.result.dataName,
        ERROR = zlConfig.global.result.errorState,
        OK = zlConfig.global.result.okState,
        fullheight = zlContext.setMaxHeihgt(0),
        ptable = null,
        upload = layui.upload,
        tableId = 'tbdept';
    var treeObj,
        fromlayerIndex,
        deptcount = {};

    var treeAction = {
        selectnode: null,
        loadGridData: function (url, param) {
            var index = layer.msg('数据查询中，请稍候...', {
                icon: 16,
                time: false,
                shade: 0.1
            });
            var isorg = param.EXPANDPROPERTY == 'org' ? true : false;
            var paramdata = {};
            var orgid;
            if (isorg) {
                paramdata = {
                    ORGID: param.RWID
                };
                orgid = param.RWID;
            } else {
                paramdata = {
                    SYS_PARENTID: param.RWID,
                    ORGID: param.ORGID
                };
                orgid = param.ORGID;
            }
            ptable.reload({
                url: url,
                method: 'post',
                where: paramdata,
                done: function (res, curr, count) {
                    layer.close(index);
                    $('#btnopenall').find('i').removeClass("layui-icon-up").addClass("layui-icon-down");
                    $('#btnopenall').find('span').text("展开全部");
                    if(isorg){
                        deptcount[orgid] =  res.obj.length;  
                    }
                }
            });
        },
        refreshselectnode: function (treeNode) {
            treeObj.setting.async.url = layui.cache['contentPath'] + '/admin/coreorg/queryorgdepttreelistbyparentid';
            treeObj.reAsyncChildNodes(treeNode, "refresh"); //异步刷新，清空后加载，加载后打开  
            treeNode['isloaded'] = true;
            // treeObj.selectNode(treeNode);
        }
    };
    //加载树
    // treeAction.loadTree();
    zltreemenu.render('orgTreeId', {
        dataurl: layui.cache['contentPath'] + '/admin/coreorg/queryorgdepttreelistbyparentid',
        searchurl: layui.cache['contentPath'] + '/admin/coreorg/queryorgdepttree',
        searchKey: 'keyvalue', // 搜索时传给后台的 对象属性名
        inner: true, // 拖拽到目标节点时，设置是否允许成为目标节点的子节点
        autoParam: ["RWID"], // 异步加载时需要自动提交父节点属性的参数
        otherParam: {
            'isnotuseddept': true
        }, // Ajax 请求提交的静态参数键值对 
        asyncChildNodes: true, // 1.zTree 的节点父节点属性锁，是否始终保持 isParent = true 2.作为搜索方式的判断依据
        dataFilter: function (treeId, parentNode, responseData) {
            if (responseData[statusName] == OK) {
                var data = responseData[dataName]
                if (data && data.length && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].EXPANDPROPERTY == 'org') {
                            data[i].icon = layui.cache['contentPath'] + '/static/image/org1.png'
                        } else {
                            data[i].icon = layui.cache['contentPath'] + '/static/image/dept.png'
                        }
                        data[i].iconSkin = 'iconPosition'
                    }
                }
                return responseData[dataName];
            } else {
                zlContext.errorMsg(responseData[msgName]);
            }
            return responseData;
        }
    }, {
            onClick: function (event, treeId, treeNode) {
                treeAction.loadGridData(layui.cache['contentPath'] + "/admin/bddept/query", treeNode);
            },
            onAsyncSuccess: function (event, treeId, treeNode, msg) {
                treeObj = $.fn.zTree.getZTreeObj(treeId);
                if (!zltreemenu.isloadsearch) {
                    var addTmpNode = function (nodes) {
                        $.each(nodes, function (k, node) {
                            if (node.EXPANDPROPERTY == "org" || node.EXPANDPROPERTY == "dept") {
                                var tmpNode = {
                                    RWID: '*',
                                    OBJNAME: '*'
                                };
                                treeObj.addNodes(node, 0, tmpNode, true);
                            }
                        });
                    }
                }
                if (zltreemenu.isloadsearch) {
                    treeObj.expandAll(true);
                }
                if (!zltreemenu.isloadsearch) {
                    if (treeNode == null) {
                        addTmpNode(treeObj.getNodes());
                    } else {
                        addTmpNode(treeNode.children);
                    }
                }
                if ((zltreemenu.isloadsearch || $('#btnTreeSearchInput').val() == '') && !zltreemenu.isExpand) {
                    var firstNode = treeObj.getNodes()[0]
                    if (treeAction.selectnode) {
                        firstNode = treeAction.selectnode;
                    }
                    if (firstNode) {
                        $('#orgTreeId').find('.noResultBox').remove();
                        treeObj.selectNode(firstNode);
                        treeAction.loadGridData(layui.cache['contentPath'] + "/admin/bddept/query", firstNode);
                    } else {
                        $('#' + tableId).siblings('div').find('div.layui-table-fixed').hide();
                        $('#' + tableId).siblings('div').find('div.layui-table-main').html('');
                        zlContext.noData($('#' + tableId).siblings('div').find('div.layui-table-main'));
                        $('#orgTreeId').append(zltreemenu.noresult)
                    }
                }
            },
            beforeExpand: function (treeId, treeNode) {
                if (!treeNode.isloaded && !zltreemenu.isloadsearch) {
                    zltreemenu.isExpand = true;
                    treeAction.refreshselectnode(treeNode);
                    if (treeNode.children) {
                        for (var i = 0; i < treeNode.children.length; i++) {
                            if (treeNode.children[i].OBJNAME == "*") {
                                treeObj.removeNode(treeNode.children[i]);
                            }
                        }
                    }
                    return false;
                } else {
                    return true;
                }
            },
            beforeDrag: function (treeID, treeNodes) {
                for (var i = 0; i < treeNodes.length; i++) {
                    if (treeNodes[i].EXPANDPROPERTY == 'org') {
                        zlContext.errorMsg('机构节点不能移动！');
                        return false;
                    }
                }
            },
            beforeDrop: function (treeId, treeNodes, targetNode, moveType) {
                if (targetNode == null) {
                    zlContext.errorMsg('不能把部门拖拽到根节点下！');
                    return false;
                }
                if ((moveType == 'prev' || moveType == 'next') && targetNode.EXPANDPROPERTY == 'org') {
                    zlContext.errorMsg('不能把部门拖拽到根节点下！');
                    return false;
                }
                if (targetNode.OBJNAME == '*') {
                    zlContext.errorMsg('不能拖拽到占位节点下!');
                    return false;
                }
                // var targetorgid = targetNode.ORGID;
                // 获取拖拽项的根节点对象
                var dragNodeRootOrgid = GetRootNodeId(treeNodes[0]),
                    targetNodeRootOrgid = GetRootNodeId(targetNode);

                if (treeNodes[0].EXPANDPROPERTY == 'org') {
                    zlContext.errorMsg('不能对机构节点进行拖拽！');
                    return false;
                }
                if (dragNodeRootOrgid != targetNodeRootOrgid) {
                    zlContext.errorMsg('不能跨机构拖拽部门！');
                    return false;
                }
                // for (var i = 0; i < targetNode.length; i++) {
                //     var orgid = targetNode[I].ORGID;
                //     if (orgid != targetorgid) {
                //         zlContext.errorMsg('不能跨机构拖拽部门！')
                //         return false;
                //     }
                // }

                function GetRootNodeId(node) {
                    if (node.level == 0) {
                        return node.ORGID;
                    }
                    var pNode = node.getParentNode();
                    if (pNode.level == 0) {
                        return pNode.ORGID;
                    } else {
                        return GetRootNodeId(pNode);
                    }
                }
            },
            beforeDragOpen: function (treeId, treeNode) {
                return false;
            },
            onDragMove: function (event, treeId, treeNodes) {
                if (treeNodes.children) {
                    for (var i = 0; i < treeNodes.children.length; i++) {
                        if (treeNodes.children.OBJNAME == "*") {
                            treeObj.removeNode(treeNodes.children[i]);
                        }
                    }
                }
            },
            onDrop: function (event, treeId, treeNodes, targetNode, moveType) {
                // 选择一个根节点
                if (moveType == null) {
                    return;
                }
                if (targetNode == null) {
                    zlContext.errorMsg("拖拽的部门需拖拽至机构下！");
                    return;
                }
                if (moveType == 'prev' || moveType == 'next') {
                    var nodes = treeObj.getSelectedNodes();
                    /*根据 zTree 的唯一标识 tId 快速获取节点 JSON 数据对象*/
                    var targetNode = treeObj.getNodeByTId(nodes[0].parentTId);
                    if (targetNode == null) {
                        zlContext.errorMsg("拖拽的部门需拖拽至机构下！");
                        return;
                    }
                }
                var sourcestreenode = treeNodes[0],
                    parentNodeRwid = targetNode.EXPANDPROPERTY == 'org' ? "" : targetNode.RWID,
                    parentsid = sourcestreenode.SYS_PARENTS,
                    isleaf = 0,
                    data = {};
                if (parentNodeRwid == '') {
                    parentsid = parentsid.substr(parentsid.indexOf(sourcestreenode.RWID), parentsid.length);
                    if (sourcestreenode.children.length == 0 || (sourcestreenode.children.length == 1 && (sourcestreenode.children)[0].RWID == '*')) {
                        isleaf = 1;
                    }
                } else {
                    parentsid = parentNodeRwid + "_" + parentsid.substr(parentsid.indexOf(sourcestreenode.RWID), parentsid.length);
                }
                data = {
                    RWID: sourcestreenode.RWID,
                    SYS_PARENTID: parentNodeRwid,
                    SYS_PARENTS: parentsid,
                    ORGID: sourcestreenode.ORGID,
                    SYS_ISLEAF: isleaf
                };
                zlContext.post(layui.cache['contentPath'] + '/admin/bddept/drag', data, function (result) {
                    if (result[statusName] == ERROR) {
                        zlContext.errorMsg(result[msgName]);
                    } else {
                        treeAction.refreshselectnode(targetNode);
                    }
                })
            }
        })

    //渲染字段列表
    ptable = treeGrid.render({
        id: tableId,
        elem: '#' + tableId,
        // url: layui.cache['contentPath'] + "/admin/bddept/query", 
        response: zlConfig.global.gridResponse,
        treeId: 'RWID', //树形id字段名称
        treeUpId: 'SYS_PARENTID', //树形父id字段名称
        treeShowName: 'OBJNAME', //以树形式显示的字段
        height: fullheight,
        limit: 999,
        cellMinWidth: 75,
        isOpenDefault: false,
        chkboxType: {
            "Y": "",
            "N": ""
        }, //父子节点的关联关系 默认值：{ "Y": "ps", "N": "ps" }
        cols: [
            [ //表头
                {
                    type: 'numbers',
                    fixed: 'left',
                    title: '#'
                }, {
                    type: 'checkbox',
                    fixed: 'left'
                }, {
                    field: 'OBJNAME',
                    title: '名称',
                    width: 200
                }, {
                    field: 'OBJCODE',
                    title: '编号',
                    width: 150
                }, {
                    field: 'SYS_SORT',
                    title: '排序',
                    width: 150
                }, {
                    field: 'STARTFLAG',
                    title: '是否启用',
                    width: 150,
                    templet: '<div><span>{{#  if(d.STARTFLAG==0){ }}  否 {{}} {{#  } else {}}  是 {{#  } }}</span></div>'
                }, {
                    fixed: 'right',
                    width: 280,
                    title: '操作',
                    align: 'center',
                    toolbar: '#barDept'
                }
            ]
        ]
    });
    zlContext.noData($('#' + tableId).siblings('div').find('div.layui-table-main'));

    var gridAction = {
        currentEditObj: undefined,
        delId: '',
        userGridedit: function (orgId, row, type, arg_readonly) {
            var readonly = arg_readonly && arg_readonly != 0 ? 'disabled' : '';
            var frm = [
                '<div class="site-block" lay-filter="divgridField"> <form id ="frmGridDept" class="layui-form"  action="">' //
                , '	<div class="layui-form-item layui-hide">' //
                , '		<div class="layui-input-block">' //
                , '			<input type="text" name="EDITTYPE" class="layui-input">' //
                , '			<input type="text" name="RWID" class="layui-input">' //
                , '			<input type="text" name="ORGID" class="layui-input">' //
                , '			<input type="text" name="SYS_PARENTS" class="layui-input">' //
                , '			<input type="text" name="SYS_PARENTID" class="layui-input">' //
                , '		</div>', '	</div>', '	<div class="layui-form-item">' //
                , '		<label class="layui-form-label">名称</label>' //
                , '		<div class="layui-input-block">' //
                , '			<input type="text" name="OBJNAME" lay-verify="required" placeholder="请输入部门名"' + readonly + '  class="layui-input" maxlength="33">' //
                , '		</div>' //
                , '	</div>' //
                , '	<div class="layui-form-item">' //
                , '		<label class="layui-form-label">编号</label>' //
                , '		<div class="layui-input-block">' //
                , '			<input type="text" name="OBJCODE" lay-verify="required" placeholder="请输入编号 " ' + readonly + '  class="layui-input" maxlength="10">' //
                , '		</div>' //
                , '	</div>' //
                , '	<div class="layui-form-item">' //
                , '		<label class="layui-form-label">排序</label>' //
                , '		<div class="layui-input-block">' //
                , '			<input type="text" name="SYS_SORT" lay-verify="required|number" maxlength="7" placeholder="请输入排序 " ' + readonly + '  class="layui-input">' //
                , '		</div>' //
                , '	</div>' //
                , '	<div class="layui-form-item">' //
                , ' 	<div class="layui-inline">' //
                , '			<label class="layui-form-label">启用</label>' //
                , '			<div class="layui-input-block">' //
                , '				<input type="checkbox"  name="STARTFLAG" valueformat="1|0" lay-skin="primary" ' + readonly + '>' //
                , '			</div>' //
                , '		</div>' //
                , '	</div>' //
                , '	<div class="layui-form-item">' //
                , '		<div class="layui-input-block">' //
                , '		  <button class="layui-btn ' + (type == 'browse' ? 'layui-hide" ' : '"') + '" lay-submit lay-filter="frmGridDept" "  ' + readonly + ' >保存</button>' //
                // , '		  <button type="reset" class="layui-btn layui-btn-primary  ' + (type == 'new' ? '" ' : 'layui-hide" ') + readonly + '>重置</button>'
                , '		</div>' //
                , '	</div>' //
                , '</form></div>' //
            ];
            layer.open({
                type: 1,
                limit: 999,
                maxmin: true, //最大化按钮
                title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '新增'),
                id: 'bddeptLayer',
                area: ['100%', '100%'],
                content: frm.join(''),
                success: function (layero, index) {
                    if (type != 'new') {
                        zlContext.autoFill($('#frmGridDept'), row);
                        $('#frmGridDept input[name=EDITTYPE]').val('edit');
                        $('#frmGridDept input[name=ORGID]').val(orgId);
                        $('#frmGridDept input[name=RWID]').val(row['RWID']);
                    } else {
                        /**设置隐藏属性*/
                        $('#frmGridDept input[name="EDITTYPE"]').val('new');
                        $('#frmGridDept input[name="ORGID"]').val(orgId);
                        if (row) {
                            if (row.EXPANDPROPERTY != undefined && row.EXPANDPROPERTY == 'org') {
                                $('#frmGridDept input[name="SYS_PARENTID"]').val('');
                                $('#frmGridDept input[name="SYS_PARENTS"]').val('');
                            } else {
                                $('#frmGridDept input[name="SYS_PARENTID"]').val(row.RWID);
                                $('#frmGridDept input[name="SYS_PARENTS"]').val(row.SYS_PARENTS);
                            }
                        }
                        $('#frmGridDept input[name="STARTFLAG"]').attr('checked', 'checked');
                        if (deptcount) {
                            $('#frmGridDept input[name="SYS_SORT"]').val(deptcount[orgId] + 1);
                        }
                        //由于layui是主动刷新需要重新刷新才能显示出状态
                    }
                    fromlayerIndex = index;
                    form.render();
                    $('#frmGridDept input[name=OBJNAME]').change(function () {
                        var v = $('#frmGridDept input[name="OBJNAME"]').val();
                        var v1 = zlPinYin.C(v);
                        $('#frmGridDept input[name="OBJCODE"]').val(v1);
                    });
                },
                cancel: function (index, layero) {
                    if (type == 'edit') {
                        zlContext.isFormDataChange('frmGridDept', gridAction.currentEditObj.data, gridAction, index);
                        return false;
                    }
                }
            });
        },
        viewRow: function (row) {
            gridAction.userGridedit(null, row, 'browse', true);
        },
        newRow: function () {
            var nodes = treeObj.getSelectedNodes(),
                checkStatus = treeGrid.checkStatus('tbdept'),
                rows = checkStatus.data,
                orgid = "";
            if (nodes.length == 0 && rows.length == 0) {
                zlContext.warnMsg('请选择机构部门节点或者勾选部门节点');
                return;
            }
            if (rows.length > 1) {
                zlContext.errorMsg("不能同时选择两个部门下增加部门！");
                return;
            } else if (rows.length == 0) {
                rows = nodes[0];
                orgid = nodes[0]['ORGID'];
            } else {
                orgid = rows[0]['ORGID'];
                rows = rows[0];
            }
            gridAction.userGridedit(orgid, rows, 'new');
        },
        editRow: function (row) {
            gridAction.userGridedit(row['ORGID'], row, 'edit');
        },
        deleteRows: function (rows) {
            if (rows.length == 0) {
                zlContext.warnMsg('请选择需要删除的部门');
                return;
            }
            var id = new Array(),
                orgid ,
                canpost = true;
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].children.length > 0) {
                    layer.msg(rows[i].OBJNAME + "部门下还有子部门，请先删除子部门");
                    canpost = false;
                    return;
                }
                // if (rows[i].HASUSER == 1) {
                //     layer.msg(rows[i].OBJNAME + "部门下还有人员，请先移除人员");
                //     canpost = false;
                //     return;
                // }
                orgid = rows[i].ORGID;
                id.push(rows[i]);
            }
            if (!canpost) {
                return;
            }
            zlContext.confirm('询问', '是否要删除选择的部门?', function (index) {
                //提交删除
                zlContext.deletePost(layui.cache['contentPath'] + '/admin/bddept/remove', id, function (result) {
                    if (result[statusName] == OK) {
                        if (id.length == 1) {
                            gridAction.delId = id[0].RWID;
                        }
                        gridAction.refresh('del');
                        zlContext.successMsg('删除成功');
                        deptcount[orgid] = deptcount[orgid] - id.length; 
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
                layer.close(index);
            });
        },
        sumbit: function (fields) {
            var editType = $('#frmGridDept input[name=EDITTYPE]').val();
            if (editType == 'new') {
                zlContext.put(layui.cache['contentPath'] + '/admin/bddept/add', fields, function (result) {
                    if (result[statusName] == OK) {
                        var node = treeObj.getSelectedNodes();
                        if (node.length > 0) {
                            var isorg = node[0].EXPANDPROPERTY == 'org' ? true : false;
                            var data = {};
                            if (isorg) {
                                data = {
                                    ORGID: node[0].RWID
                                };
                                deptcount[node[0].RWID] = deptcount[node[0].RWID] + 1;
                            } else {
                                data = {
                                    SYS_PARENTID: node[0].RWID
                                };
                                deptcount[node[0].ORGID] = deptcount[node[0].ORGID] + 1;
                            }
                            gridAction.refresh(editType, data);
                        }
                        layer.close(fromlayerIndex);
                        zlContext.successMsg('保存成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            }
            if (editType == 'edit') {
                zlContext.post(layui.cache['contentPath'] + '/admin/bddept/modify', fields, function (result) {
                    if (result[statusName] == OK) {
                        gridAction.refresh(editType, fields);
                        layer.close(fromlayerIndex);
                        zlContext.successMsg('保存成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            }
            return false;
        },
        refresh: function (type, row) {
            /**刷新行 */
            // var selectnode = treeObj.getSelectedNodes();
            // if (type == 'edit' && gridAction.currentEditObj) {
            //     gridAction.currentEditObj.update(row);
            //     if(selectnode.length>0){
            //         // 更新的是选择的节点
            //         if(selectnode[0].RWID==row.RWID){
            //             selectnode[0].OBJNAME = row.OBJNAME
            //             treeObj.updateNode(selectnode[0]);
            //         }else{
            //             treeAction.refreshselectnode(selectnode[0]);     
            //         }
            //     }
            //     form.render();
            // }
            var selectnode = treeObj.getSelectedNodes();

            // 刷新左侧的机构部门树
            if (selectnode.length > 0) {
                var node = selectnode[0];
                if(type=='edit'&&node.RWID==row.RWID){
                    node.OBJNAME = row.OBJNAME
                    treeObj.updateNode(node);
                }else{
                    if (type == 'del' && selectnode[0].RWID == gridAction.delId) {                 
                        if (selectnode[0].getParentNode()) {
                            node = selectnode[0].getParentNode();
                            selectnode = [node];
                        }                       
                        treeObj.selectNode(node)
                        treeAction.selectnode = node;
                    } 
                    treeAction.refreshselectnode(node);
                    treeAction.selectnode = node;     
                }           
                    
            }
            treeAction.loadGridData(layui.cache['contentPath'] + "/admin/bddept/query", selectnode[0]);
        }
    }
    // 展开或折叠全部
    $('#btnopenall').on('click', function () {
        var treedata = treeGrid.getDataTreeList('tbdept');
        if ($(this).find('i').hasClass("layui-icon-down")) {
            $(this).find('i').removeClass("layui-icon-down").addClass("layui-icon-up");
            $(this).find('span').text("收起全部");
        } else {
            $(this).find('i').removeClass("layui-icon-up").addClass("layui-icon-down");
            $(this).find('span').text("展开全部");
        }
        treeGrid.treeOpenAll('tbdept', !treedata[0][treeGrid.config.cols.isOpen]);
    });
    $('#btnDeptNew').on('click', function () {
        gridAction.newRow();
    });
    $('#btnDeptDelete').on('click', function () {
        var checkStatus = treeGrid.checkStatus('tbdept'),
            rows = checkStatus.data;
        gridAction.deleteRows(rows);
    });
    $('#btnOutportModel').on('click', function () {
        location.href=layui.cache['contentPath']+'/static/appdata/filesres/excelTemplate/BddeptImportModel.xls';
    });

    treeGrid.on('tool(tbdept)', function (obj) {
        var row = obj.data, //获得当前行数据
            layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        if (layEvent === 'detail') { //查看
            gridAction.viewRow(row)
        } else if (layEvent === 'del') { //删除
            gridAction.currentEditObj = obj;
            gridAction.deleteRows([row]);
        } else if (layEvent === 'edit') { //编辑
            gridAction.currentEditObj = obj;
            gridAction.editRow(row);
        }
    });
    //提交
    form.on('submit(frmGridDept)', function (frm) {
        if ($(frm.elem).hasClass('getField')) {
            gridAction.newFields = frm.field;
            return false;
        }
        return gridAction.sumbit(frm.field);
    });

    upload.render({
        elem: '#btnImport',
        accept: 'file', //所有的文件
        url: layui.cache['contentPath'] + '/core/excel/excelin',
        done: function (res) {
            if (res[statusName] != OK) {
                // $('#imgPrieviewPic').attr('src', '');
                return zlContext.errorMsg('导入失败:' + res[msgName]);
            } else {
                zlContext.successMsg('导入成功');
                gridAction.refresh('new', null);
            }
        },
        error: function () {
            zlContext.errorMsg('上传失败');
        }
    });

    $(window).on('resize', function () {
        zlContext.setMaxHeihgt(0);
        ptable.reload('tbdept');
    }).resize();
});